//
//  ActionDetailViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/4/23.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "ActionDetailViewController.h"
#import "ActionItemModel.h"
#import "ActionDetailInfoCell.h"
#import "UIView+LLXAlertPop.h"


@interface ActionDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,AxcPhotoBrowserDelegate>
@property (weak, nonatomic) IBOutlet UITableView *selfTableView;
@property (weak, nonatomic) IBOutlet UIButton *conectBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottomLayout;
@property (nonatomic,strong) ActionItemModel *itemModel;
@end

@implementation ActionDetailViewController
-(void)rightAction:(UIButton *)sender
{
    
}
- (IBAction)callPhone:(UIButton *)sender {
    
    NSArray *arrayTitle = [self.itemModel.phone componentsSeparatedByString:@","];
    UIColor *color = [UIColor AxcUI_colorWithHexCode:@"#676767"];
    [self.view createAlertViewTitleArray:arrayTitle textColor:color font:[UIFont systemFontOfSize:16] actionBlock:^(UIButton * _Nullable button, NSInteger didRow) {
        //获取点击事件
        NSLog(@"%@,%ld",button.currentTitle,(long)didRow);
        //                lab.text = [NSString stringWithFormat:@"%@,下标%ld",button.currentTitle,(long)didRow];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", button.currentTitle];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        }
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    mNavitationTitle(@"互动详情");
    [self customNavigationItems];
//    [self addRightBarButtonItemWithTitle:@"分享" action:@selector(rightAction:)];
    [self loadAllHuDongs];
    if (self.isSelf) {
        self.conectBtn.hidden = YES;
        self.toBottomLayout.constant = 0;
    }
}
#pragma mark -
#pragma mark - **************** tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.itemModel) {
        return 2;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        ActionDetailInfoCell * itemCell = mGetTableViewCell(@"actionDetailInfoCell");
        [itemCell reloadViewForModel:self.itemModel];
        return itemCell;
    }
    if (indexPath.row == 1) {
        UITableViewCell * itemCell = mGetTableViewCell(@"imageCell");
        UICollectionView * collectionView = mViewByTag(itemCell.contentView, 100, UICollectionView);
        collectionView.dataSource = self;
        collectionView.delegate = self;
        [collectionView reloadData];
        return itemCell;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return [tableView fd_heightForCellWithIdentifier:@"actionDetailInfoCell" configuration:^(ActionDetailInfoCell *cell) {
            //                    cell.desLabel.text = @"藏友您好，您发的这件藏品为清代光绪时期青花刀人物抱月瓶，胎釉青花及画均符合光绪时期特征，近年来回流较多，价值在小几千元，喜欢可玩。";
            [cell reloadViewForModel:self.itemModel];
        }];
    }else{
        NSArray * imagesArr = [self.itemModel.image componentsSeparatedByString:@","];
        if (imagesArr.count <= 2) {
            return (mScreenWidth-40)/2 + 10;
        }else if(imagesArr.count <= 4){
            return (mScreenWidth-40) + 20;
        }else{
            return (mScreenWidth-40)*3/2 + 30;
        }
    }
    return 100;
}
#pragma mark uicollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray * imagesArr = [self.itemModel.image componentsSeparatedByString:@","];
    return imagesArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * imagesArr = [self.itemModel.image componentsSeparatedByString:@","];
    UICollectionViewCell * cell = mGetCollectionViewCell(@"itemCell", indexPath);
    UIImageView * logoImage = mViewByTag(cell.contentView, 100, UIImageView);
    [logoImage sd_setImageWithURL:imagesArr[indexPath.row] placeholderImage:mImageByName(@"")];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    125/170 = (mScreenWidth-60)*2/5 / h
    return CGSizeMake((mScreenWidth-40)/2, (mScreenWidth-40)/2);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * imagesArr = [self.itemModel.image componentsSeparatedByString:@","];
    AxcUI_PhotoBrowser *browser = [[AxcUI_PhotoBrowser alloc] init];
    browser.axcUI_sourceImagesContainerView = self.view;                        // 设置父视图
    browser.axcUI_imageCount = imagesArr.count;                            // 设置图片总数
    browser.axcUI_currentImageIndex = (int )indexPath.row;                      // 设置当前索引
    browser.axcUI_photoBrowserDelegate = self;                                  // 设置代理回调
    browser.axcUI_convertRectView = collectionView;                                       // 设置扩展动画/放大效果的View
    //            browser.axcUI_progressSize = CGSizeMake(30, 30);                            // 设置加载指示器大小
    //                browser.axcUI_progressViewStyle = self.progressSegmented.selectedSegmentIndex;    // 设置加载指示器风格
    //            browser.axcUI_pageTypeMode = AxcPhotoBrowserPageControlStyleNumPage;                                // 设置索引展示模式
    browser.axcUI_saveType = AxcPhotoBrowserStyleButtonSave;                     // 设置互动模式：按钮保存/长摁保存
    // 如果带有高度适配参数则需要调整适应
    //    browser.axcUI_automaticallyAdjustsScrollViewInsets = self.rootVC.automaticallyAdjustsScrollViewInsets;
    [browser AxcUI_show];
}
#pragma mark - AxcUI_photoBrowser 代理区
- (void)AxcUI_photoBrowser:(AxcUI_PhotoBrowser *)browser
              saveTypeMode:(AxcPhotoBrowserSaveStyle)saveTypeMode
                     Image:(UIImage *)saveImage{
    // 当图片发生互动（长摁/按钮）保存时发生的回调。saveTypeMode根据之前设定的互动模式来反馈相应的操作
    if (saveTypeMode == AxcPhotoBrowserStyleLongTapSave) {
        NSLog(@"长摁");
    }else{
        UIImageWriteToSavedPhotosAlbum(saveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
        NSLog(@"按钮");
    }
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [AxcUI_Toast AxcUI_showCenterWithText:@"保存错误"];
    }else{
        [AxcUI_Toast AxcUI_showCenterWithText:@"已存储到相册"];
    }
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}
- (UIImage *)AxcUI_photoBrowser:(AxcUI_PhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    // 返回当前索引的placeholderImage，这里使用小图加载的缓存作为占位
    //    return [Axc_WebimageCache AxcUI_getAxcImageWithCacheKey:self.dataArray[index]];
    return nil;
}
- (NSURL *)AxcUI_photoBrowser:(AxcUI_PhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    // 返回当前索引的高清图
    //    NSString *HDurlStr = [self.dataArray[index] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    // 替换关键字来实现高清/动图的加载
    NSArray * imagesArr = [self.itemModel.image componentsSeparatedByString:@","];
//    NSArray * urlArr = [self.EVAmodel.imgList[index][@"url"] componentsSeparatedByString:@"?"];
    return [NSURL URLWithString:imagesArr[index]];
}
//这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10;
}
//两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 15, 10, 15);
}
#pragma mark -
#pragma mark - **************** 数据请求
-(void)loadAllHuDongs
{
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
    setDickeyobj(parameters, self.bbsId, @"bbsId");
    setDickeyobj(parameters, @"1", @"add");
    [PPNetworkHelper POST:app_circle_getBbsInfoById parameters:parameters success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            self.itemModel = [[ActionItemModel alloc]init];
            [self.itemModel setValuesForKeysWithDictionary:responseObject[@"data"]];
            self.itemModel.ID = responseObject[@"data"][@"id"];
        }else{
            
        }
        [self.selfTableView reloadData];
    } failure:^(NSError *error) {
        
    } showLoading:nil];
}


@end
